﻿using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Zero.WebAPI.Framework.Config.Helper;

namespace Zero.WebAPI.Framework.Helper.Encrypt
{
    public class JwtHelper
    {
        public static string GenerateToken(string data)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigHelper.Get<string>("Jwt:Key")));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier,data)
            };

            var token = new JwtSecurityToken(
                ConfigHelper.Get<string>("Jwt:Issuer"),
                ConfigHelper.Get<string>("Jwt:Audience"),
                claims,
                expires: DateTime.Now.AddMinutes(Convert.ToDouble(ConfigHelper.Get<int>("Jwt:ExpiryInMinutes"))),
                signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public static List<Claim> ParseToken(string token)
        {
            List<Claim> claims = null;
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            try
            {
                JwtSecurityToken jwtToken = handler.ReadJwtToken(token);
                claims = jwtToken.Claims.ToList();
            }
            catch (Exception ex)
            {
                LogHelper.Error($"token: {token}，解析异常", ex);
            }
            return claims;
        }

        public static JwtSecurityToken ParseToken2(string token)
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            return handler.ReadJwtToken(token);
        }

        public static bool IsExpired(string token)
        {
            try
            {
                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                JwtSecurityToken jwtToken = handler.ReadJwtToken(token);

                // 检查token是否过期
                return jwtToken.ValidTo < DateTime.UtcNow;
            }
            catch
            {
                // 如果解析token失败，则认为已过期
                return true;
            }
        }

        // 新增方法：验证token是否有效（包括签名和过期时间）
        public static bool ValidateToken(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var validationParameters = GetValidationParameters();

                // 这会验证签名和过期时间
                tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private static TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = ConfigHelper.Get<string>("Jwt:Issuer"),
                ValidAudience = ConfigHelper.Get<string>("Jwt:Audience"),
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigHelper.Get<string>("Jwt:Key")))
            };
        }
    }
}
